import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package_info_service.dart';
import 'storage_service.dart';
import 'app_config_service.dart';
import 'dio_service.dart';
import 'permission_service.dart';
import 'user_service.dart';
import '../routers/route_service.dart';

/// 服务定位器 - 统一管理所有GetX服务的注册和初始化
class ServiceLocator {
  // ==================== 服务配置列表 ====================
  
  /// 服务配置模型
  static final List<ServiceConfig> _serviceConfigs = [
    ServiceConfig<PackageInfoService>(
      name: 'PackageInfoService',
      icon: '📦',
      description: '应用包信息服务',
      initAsync: true,
    ),
    ServiceConfig<StorageService>(
      name: 'StorageService',
      icon: '💾',
      description: '本地存储服务',
      initAsync: true,
    ),
    ServiceConfig<AppConfigService>(
      name: 'AppConfigService',
      icon: '⚙️',
      description: '应用配置服务',
      initAsync: true,
    ),
    ServiceConfig<DioService>(
      name: 'DioService',
      icon: '🌐',
      description: '网络服务',
      initAsync: true,
    ),
    ServiceConfig<PermissionService>(
      name: 'PermissionService',
      icon: '🔐',
      description: '权限服务',
      initAsync: false, // 同步初始化
    ),
    ServiceConfig<RouteService>(
      name: 'RouteService',
      icon: '🧭',
      description: '路由服务',
      initAsync: false, // 同步初始化
    ),
    ServiceConfig<UserService>(
      name: 'UserService',
      icon: '👤',
      description: '用户服务',
      initAsync: true,
    ),
  ];
  
  /// 初始化所有服务
  static Future<void> init() async {
    debugPrint('🚀 开始初始化服务...');
    
    try {
      for (final config in _serviceConfigs) {
        await config.register();
      }
      
      debugPrint('✅ 所有服务初始化完成');
      
      // 打印服务注册状态（仅在调试模式下）
      if (kDebugMode) {
        _printServiceStatus();
      }
      
    } catch (e) {
      debugPrint('❌ 服务初始化失败: $e');
      rethrow;
    }
  }
  
  // ==================== 服务便捷访问方法 ====================
  
  static PackageInfoService get packageInfo => Get.find<PackageInfoService>();
  static StorageService get storage => Get.find<StorageService>();
  static AppConfigService get appConfig => Get.find<AppConfigService>();
  static DioService get network => Get.find<DioService>();
  static PermissionService get permission => Get.find<PermissionService>();
  static RouteService get route => Get.find<RouteService>();
  static UserService get user => Get.find<UserService>();
  
  // ==================== 服务管理方法 ====================
  
  /// 检查服务是否已注册
  static bool isServiceRegistered<T>() {
    return Get.isRegistered<T>();
  }
  
  /// 获取服务统计信息
  static Map<String, dynamic> getServiceStats() {
    return {
      'registeredServices': _serviceConfigs
          .where((config) => config.isRegistered)
          .map((config) => config.name)
          .toList(),
      'totalServices': _getRegisteredServiceCount(),
      'initTime': DateTime.now().toIso8601String(),
    };
  }
  
  /// 获取已注册服务数量
  static int _getRegisteredServiceCount() {
    return _serviceConfigs.where((config) => config.isRegistered).length;
  }
  
  /// 打印服务注册状态（调试用）
  static void _printServiceStatus() {
    debugPrint('==================== 服务状态 ====================');
    
    for (final config in _serviceConfigs) {
      final status = config.isRegistered ? '✅' : '❌';
      final state = config.isRegistered ? '已注册' : '未注册';
      debugPrint('$status ${config.name}: $state');
    }
    
    debugPrint('总计: ${_getRegisteredServiceCount()} 个服务已注册');
    debugPrint('================================================');
  }
  
  /// 重新初始化服务（谨慎使用）
  static Future<void> reinit() async {
    debugPrint('🔄 重新初始化服务...');
    
    try {
      // 清理现有服务
      dispose();
      
      // 重新初始化
      await init();
      
      debugPrint('✅ 服务重新初始化完成');
    } catch (e) {
      debugPrint('❌ 服务重新初始化失败: $e');
      rethrow;
    }
  }
  
  /// 清理所有服务（应用退出时调用）
  static void dispose() {
    debugPrint('🧹 清理所有服务...');
    
    try {
      // 反向清理服务（后注册的先清理）
      for (final config in _serviceConfigs.reversed) {
        config.dispose();
      }
      
      debugPrint('✅ 所有服务已清理');
    } catch (e) {
      debugPrint('❌ 服务清理失败: $e');
    }
  }
  
  /// 获取服务详细信息
  static List<Map<String, dynamic>> getServiceDetails() {
    return _serviceConfigs.map((config) => config.toMap()).toList();
  }
}

/// 服务配置模型
class ServiceConfig<T> {
  final String name;
  final String icon;
  final String description;
  final bool initAsync;
  
  const ServiceConfig({
    required this.name,
    required this.icon,
    required this.description,
    this.initAsync = true,
  });
  
  /// 检查服务是否已注册
  bool get isRegistered => Get.isRegistered<T>();
  
  /// 注册服务
  Future<void> register() async {
    debugPrint('$icon 注册$description...');
    
    // 创建服务实例（使用泛型工厂）
    final service = _createServiceInstance();
    Get.put<T>(service, permanent: true);
    
    // 手动调用异步初始化
    if (initAsync) {
      await _initServiceAsync(service);
    } else {
      _initServiceSync(service);
    }
  }
  
  /// 异步初始化服务
  Future<void> _initServiceAsync(dynamic service) async {
    if (service is PackageInfoService) {
      await service.onInit();
    } else if (service is StorageService) {
      await service.onInit();
    } else if (service is AppConfigService) {
      await service.onInit();
    } else if (service is DioService) {
      await service.onInit();
    } else if (service is UserService) {
      await service.onInit();
    }
  }
  
  /// 同步初始化服务
  void _initServiceSync(dynamic service) {
    if (service is PermissionService) {
      service.onInit();
    } else if (service is RouteService) {
      service.onInit();
    }
  }
  
  /// 清理服务
  void dispose() {
    if (isRegistered) {
      Get.delete<T>();
      debugPrint('🧹 $name 已清理');
    }
  }
  
  /// 创建服务实例
  T _createServiceInstance() {
    // 使用类型判断创建对应的服务实例
    if (T == PackageInfoService) {
      return PackageInfoService() as T;
    } else if (T == StorageService) {
      return StorageService() as T;
    } else if (T == AppConfigService) {
      return AppConfigService() as T;
    } else if (T == DioService) {
      return DioService() as T;
    } else if (T == PermissionService) {
      return PermissionService() as T;
    } else if (T == RouteService) {
      return RouteService() as T;
    } else if (T == UserService) {
      return UserService() as T;
    } else {
      throw Exception('未知的服务类型: $T');
    }
  }
  
  /// 转换为Map（用于调试）
  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'icon': icon,
      'description': description,
      'isRegistered': isRegistered,
      'initAsync': initAsync,
      'type': T.toString(),
    };
  }
  
  @override
  String toString() {
    return 'ServiceConfig<$T>{name: $name, isRegistered: $isRegistered}';
  }
}
